﻿using DataLayer.Repo;
using DataLayer.Types;
using StructureMap;
using StructureMap.Attributes;
using ViewModel;

namespace IOCContainer
{
    public class IoCBootstrapper : IBootstrapper
    {
        private static bool _hasStarted;

        public void BootstrapMe()
        {
            log4net.LogManager.GetLogger(GetType()).Info("Bootstrapping IOC container");

            ObjectFactory.Initialize(x =>
            {
                // We put the properties for an NHibernate ISession
                // in the StructureMap.config file, so this file
                // must be there for our application to
                // function correctly
                x.UseDefaultStructureMapConfigFile = true;
                x.IgnoreStructureMapConfig = true;
//
//                x.AddRegistry(new CoreRegistry());
//                x.AddRegistry(new SearchRegistry());
//                x.AddRegistry(new WebCoreRegistry());
//                x.AddRegistry(new RuleRegistry());

                x.ForRequestedType<MainWindowViewModel>().CacheBy(InstanceScope.Singleton).TheDefaultIsConcreteType<MainWindowViewModel>();
                x.ForRequestedType<IRepository<BudgetItem>>().CacheBy(InstanceScope.Singleton).TheDefaultIsConcreteType<GenericRepository<BudgetItem>>();
                x.ForRequestedType<IRepository<FrequencyItem>>().CacheBy(InstanceScope.Singleton).TheDefaultIsConcreteType<GenericRepository<FrequencyItem>>();
                x.ForRequestedType<IRepository<CategoryItem>>().CacheBy(InstanceScope.Singleton).TheDefaultIsConcreteType<GenericRepository<CategoryItem>>();
                x.ForRequestedType<IRepository<BalanceType>>().CacheBy(InstanceScope.Singleton).TheDefaultIsConcreteType<GenericRepository<BalanceType>>();
                x.ForRequestedType<IRepository<SavingsPlan>>().CacheBy(InstanceScope.Singleton).TheDefaultIsConcreteType<GenericRepository<SavingsPlan>>();
            });
        }

        public static void Restart()
        {
            if (_hasStarted)
            {
                ObjectFactory.ResetDefaults();
            }
            else
            {
                Bootstrap();
                _hasStarted = true;
            }
        }

        public static void Bootstrap()
        {
            new IoCBootstrapper().BootstrapMe();
        }
    }
}
